import 'dart:async';
import 'package:carousel_slider/carousel_slider.dart';
import 'package:event_bus/event_bus.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
import 'package:gameplay_flutter/lib_basemodel/home/room_list_model.dart';
import 'package:gameplay_flutter/lib_runtime/extension/widget/widget_wrapper.dart';
import 'package:gameplay_flutter/m_main/home/compoents/drawer_add_room.dart';
import 'package:gameplay_flutter/m_main/home/compoents/drawer_list.dart';
import 'package:gameplay_flutter/m_main/home/compoents/mine_tabs.dart';
import 'package:gameplay_flutter/m_main/home/compoents/popular_tabs.dart';
import 'package:ones/ui.dart';
import 'package:provider/provider.dart';
import '../../generated/assets.dart';
import '../../lib_basemodel/chat_room/kh_chat_room_enter_model.dart';
import '../../lib_basemodel/chat_room/kh_chat_room_info_model.dart';
import '../../lib_baseview/lib_baseview.dart';
import '../../lib_baseview/theme/jr.dart';
import '../../lib_baseview/utils/cache_util.dart';
import '../../lib_baseview/widget/empty_view/jr_empty_view.dart';
import '../../lib_baseview/widget/web/common_web_view.dart';
import '../../lib_chat/friend_search/index.dart';
import '../../lib_network/old/url_config.dart';
import '../../lib_runtime/common/lanuage_util.dart';
import '../../lib_runtime/logger.dart';
import '../../lib_runtime/utils/throttle.dart';
import '../../lib_runtime/web_url_const.dart';
import '../../lib_user/user_manager.dart';
import '../../m_chatroom/src/interface/room_page.dart';
import '../../m_login/select_country/select_country_model.dart';
import '../../m_me/me_controller.dart';
import '../../resource/language/generated/l10n.dart';
import '../main/animated_floation_action_button.dart';
import '../main_page_model.dart';
import 'compoents/fresh_components.dart';
import 'controller/child_controller.dart';
import 'home_controller.dart';
import 'home_countries/home_countries.dart';
class NewHomePage extends StatefulWidget {
  NewHomePage({super.key}) {
    Get.put(HomeController());
  }
  @override
  State<NewHomePage> createState() => NewHomePageState();
}
class NewHomePageState extends State<NewHomePage>
    with SingleTickerProviderStateMixin {
  final GlobalKey<AnimatedFloatingActionButtonState> animatedFloatingKey =
  GlobalKey<AnimatedFloatingActionButtonState>();
  final ChildController _childController = ChildController();
  EventBus eventBus = EventBus();
  late TabController _tabController;
  late final MeController meController;
  final EasyRefreshController _refreshControllerRoom = EasyRefreshController();
  late HomeController _homeController;
  final _gsOpen = false;
  bool hasMore = false;
  bool noMore = false;
  String country = UserManager.instance.currentUser?.country ?? '';
  // BaseRspResult<HomePageAbundantCardListRsp>? _gsCardRsp;
  double get tabBarH => 44.0;
  int currentIndex = 0;
  int pageNum = 0;
  int swiperIndex = 0;
  late List<String> topNameList = [T.current.h1_top_room,T.current.h1_top_gifter_room,T.current.h1_top_charm_room];
  int scrollerOffset = 0;
  bool DrawerListState = false;
  final localCode = CacheUtil.get(CacheKeys.languageCode);
  final List<String> imgList = [
    'assets/images/home/rooms_banner.png',
    'assets/images/home/rooms_banner.png',
    'assets/images/home/rooms_banner.png',
  ];
  @override
  void initState() {
    super.initState();
    _homeController = Get.find<HomeController>();
    meController = Get.put(MeController());
    _tabController = TabController(
      length: 3,
      vsync: this,
    );
    // DrawerListState = false;
    // DrawerAddRoomKey.currentState?.close();
    _tabController.addListener(() {
      setState(() {
        currentIndex = _tabController.index;
      });
      if (_tabController.index == 1) {
        _homeController.loadPopularData(
            _homeController.roomTagsList.value[0].roomCategoryIds as String,'refresh',1);
        _homeController.loadPopularTop('5');
        _homeController.loadPopularTop('2');
        _homeController.loadPopularTop('1');
      }
      if (_tabController.index == 2) {
        if(_homeController.roomTypesList.value.length > 0){
          _homeController.loadMineData(
              0, _homeController.roomTypesList.value[2].type as int,'refresh',1);
          _homeController.loadMineData(
              1, _homeController.roomTypesList.value[1].type as int,'refresh',1);
          _homeController.loadMineData(
              2, _homeController.roomTypesList.value[0].type as int,'refresh',1);
        } else {
          _homeController.loadRoomTags();
          if(_homeController.roomTypesList.value.length > 0){
            _homeController.loadMineData(
                0, _homeController.roomTypesList.value[2].type as int,'refresh',1);
            _homeController.loadMineData(
                1, _homeController.roomTypesList.value[1].type as int,'refresh',1);
            _homeController.loadMineData(
                2, _homeController.roomTypesList.value[0].type as int,'refresh',1);
          }
        }
      }
    });
    ever(meController.languageCode, (code) {
      setState(() {
        topNameList = [T.current.h1_top_room,T.current.h1_top_gifter_room,T.current.h1_top_charm_room];
      });
      _onLocaleChange();
    });
    ///上报首次进入首页时间
    if (!CacheUtil.getBool(CacheKeys.userHasEnterHomePageKey, false)) {
      // String dateStr = formatDate(DateTime.now(),
      //     [yyyy, '-', mm, '-', dd, ' ', HH, ':', nn, ':', ss, '.', SSS]);
      // Reporter.userSetOnce({'first_enter_time': dateStr});
      CacheUtil.setBool(CacheKeys.userHasEnterHomePageKey, true);
      _loadGsCard();
    }
  }
  void _onLocaleChange(){
    _homeController.loadData(UserManager.instance.currentUser?.country ?? '', 'refresh', 1);
    _homeController.loadRoomTags();
    _homeController.loadMineTypes();
  }
  _loadGsCard() async {
    // _gsCardRsp = await RtcApi.instance.getHomeCardList();
    // _gsOpen = (_gsCardRsp?.data?.cards.isNotEmpty ?? false);
    if (mounted) setState(() {});
  }

  bool get showRedPoint =>
      !CacheUtil.getBool(CacheKeys.userHasShowHomeRedPageKey, false) &&
          !_gsOpen;
  Future<void> _onRefreshRoom() async {
    _refreshControllerRoom.finishLoad(noMore: false);
    await _homeController.loadData(UserManager.instance.currentUser?.country ?? '','refresh',1);
    setState(() {
      noMore = false;
      pageNum = 1;
    });
    // _refreshControllerMarket.finishRefresh(success: true);
  }
  Future<void> _onLoadRoom() async {
    if(_homeController.recommend.value.length == 0){
      setState(() {
        noMore = true;
      });
    } else {
      if(!noMore){
        setState(() {
          pageNum++;
          hasMore = true;
        });
        var status =  await _homeController.loadData(UserManager.instance.currentUser?.country ?? '','more', pageNum++);
        if(!status){
          _refreshControllerRoom.finishLoad(noMore: true);
        }
      } else {
        setState(() {
          noMore = true;
        });
      }
    }
    // _refreshControllerMarket.finishRefresh(success: true);
  }
  void onDataChange(val) {
    if (val == 'left') {
      if (_tabController.index > 0) {
        _tabController.animateTo(0);
      }
    }
    if (val == 'right') {
      _tabController.animateTo(2);
    }
  }
  void onDataChangeMine(val) {
    print({val,LanguageUtil().isRTL()});
    if (val == 'left' &&  !LanguageUtil().isRTL()) {
      if (_tabController.index > 0) {
        _tabController.animateTo(1);
      }
    } else if(val == 'right' &&  LanguageUtil().isRTL()) {
      _tabController.animateTo(1);
    }
  }
  Widget body(controller) {
    return Stack(children: [
      Container(
        height: 100,
        decoration: const BoxDecoration(
          image: DecorationImage(
            image: AssetImage(Assets.homeTabBg),
            repeat: ImageRepeat.repeat,
          ),
        ),
      ),
      currentIndex == 0?Image(image:  AssetImage(Assets.homeHomeTabBg),width: 162.w, fit: BoxFit.fitWidth,):Container(),
      SafeArea(
        child: DefaultTabController(
          length: 3,
          child: Column(
            children: [
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Expanded(
                    child: TabBar(
                      controller: _tabController,
                      tabAlignment: TabAlignment.start,
                      padding: EdgeInsets.zero,
                      dividerColor: Colors.transparent,
                      isScrollable: true,
                      // indicatorPadding:const EdgeInsets.symmetric(vertical: 20),
                      indicator: const UnderlineTabIndicator(
                        borderSide: BorderSide.none, // 无边框
                      ),
                      labelStyle: const TextStyle(
                          color: Color(0xff1B1B1B),
                          fontSize: 18,
                          fontWeight: FontWeight.w600),
                      unselectedLabelStyle: const TextStyle(
                          color: Color(0xffA397DE), fontSize: 18),
                      tabs: [
                        Tab(
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              const SizedBox(
                                height: 9,
                              ),
                              Text(T.current.h1_recommend),
                              currentIndex == 0
                                  ? Container(
                                width: 34,
                                height: 4,
                                decoration: const BoxDecoration(
                                    color: Color(0xff8A72FE),
                                    borderRadius: BorderRadius.all(
                                        Radius.circular(5))),
                              )
                                  : const SizedBox(
                                width: 34,
                                height: 4,
                              )
                            ],
                          ),
                        ),
                        Tab(
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              const SizedBox(
                                height: 9,
                              ),
                              Text(T.current.h1_popular),
                              currentIndex == 1
                                  ? Container(
                                width: 34,
                                height: 4,
                                decoration: const BoxDecoration(
                                    color: Color(0xff8A72FE),
                                    borderRadius: BorderRadius.all(
                                        Radius.circular(5))),
                              )
                                  : const SizedBox(
                                width: 34,
                                height: 4,
                              )
                            ],
                          ),
                        ),
                        Tab(
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              const SizedBox(
                                height: 9,
                              ),
                              Text(T.current.h1_mine),
                              currentIndex == 2
                                  ? Container(
                                width: 34,
                                height: 4,
                                decoration: const BoxDecoration(
                                    color: Color(0xff8A72FE),
                                    borderRadius: BorderRadius.all(
                                        Radius.circular(5))),
                              )
                                  : const SizedBox(
                                width: 34,
                                height: 4,
                              )
                            ],
                          ),
                        ),
                      ],
                    ),
                  ),
                  Image.asset(Assets.homeIcSort, width: 28, height: 28)
                      .onClick(() {
                    String url =
                        '${UrlConfig.pageDomain}${WebUrlConst.ranks.path}';
                    CommonWebView.show(context, url);
                  }),
                  const SizedBox(
                    width: 9,
                  ),
                  Image.asset(Assets.homeIcSearch, width: 28, height: 28)
                      .onClick(() {
                    Get.to(() => const FriendSearchPage());
                  }),
                  const SizedBox(
                    width: 10,
                  ),
                  // Image.asset(Assets.discoverSearch, width: 28, height: 28).marginRight(16),
                ],
              ),
              Expanded(
                child: TabBarView(controller: _tabController, children: [
                  _recommend(context, controller),
                  _popular(context, controller),
                  _mine(context, controller),
                ]),
              ),
            ],
          ),
        ),
      ),
      DrawerList(
        isOpen: DrawerListState,
        callback: (val) {
          _homeController.loadData(val,'refresh',1);
          setState(() {
            country = val;
          });
        },
        controller: _childController,
      ),
      DrawerAddRoom(key: DrawerAddRoomKey, controller: _homeController),
    ]);
  }
  Widget _recommend(BuildContext context, controller) {
    return EasyRefresh(
        onRefresh: _onRefreshRoom,
        onLoad: _onLoadRoom,
        header: buildCustomHeader,
        footer:buildCustomFooter,
        controller: _refreshControllerRoom,
        child: SingleChildScrollView(
            child: Container(
              decoration: const BoxDecoration(
                  image: DecorationImage(image: AssetImage(Assets.homeHomeBodyBg),fit: BoxFit.cover)
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  const SizedBox(
                    height: 10,
                  ),
                  homeSwiper(context, _homeController),
                  Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [
                    Text(T.current.h1_countries)
                        .fontSize(20)
                        .fontWeight(FontWeight.bold)
                        .paddingSymmetric(horizontal: 12, vertical: 3),
                    Row(
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        Text(T.current.h1_more)
                            .fontSize(12)
                            .color(const Color(0xffC1C1C1))
                            .paddingSymmetric(vertical: 3),
                        RotatedBox(
                          quarterTurns:LanguageUtil().isRTL()? 2 : 0, // 180° = 2 * 90°
                          child: const Image(
                            image: AssetImage(Assets.homeRight),
                            width: 10,
                            height: 10,
                          ),
                        ),
                        const SizedBox(
                          width: 10,
                        )
                      ],
                    ).onClick(() {
                      setState(() {
                        DrawerListState = true;
                      });
                      _childController.performAction();
                      // Get.to(const HomeCountriesPage( country: 'Oman',));
                    }),
                  ]),
                  _countries(context),
                  Text(T.current.h1_chat_room)
                      .fontSize(20)
                      .fontWeight(FontWeight.bold)
                      .paddingSymmetric(horizontal: 12, vertical: 3),
                  const SizedBox(
                    height: 10,
                  ),
                  Container(
                    padding: const EdgeInsets.symmetric(horizontal: 10),
                    child: controller.recommend.value.length > 0
                        ? MasonryGridView.count(
                      crossAxisCount: 1,
                      mainAxisSpacing: 6,
                      crossAxisSpacing: 4,
                      shrinkWrap: true,
                      physics: const NeverScrollableScrollPhysics(),
                      itemCount: controller.recommend.length,
                      itemBuilder: (context, index) {
                        var newColors = 0;
                        var newBgColors = 0;
                        var roomItem = controller.recommend.value[index];
                        if (roomItem.roomCategoryColor != null) {
                          String color = '0xff' +
                              roomItem.roomCategoryColor.split('#')[1];
                          newColors = color.toInt();
                        } else {
                          newColors = 0xffc1c1c1;
                        }
                        if (roomItem.backgroundUrl != null) {
                          String bgColor =
                              '0xff' + roomItem.backgroundUrl.split('#')[1];
                          newBgColors = bgColor.toInt();
                        } else {
                          newBgColors = 0xffc1c1c1;
                        }
                        return Container(
                          decoration: const BoxDecoration(
                              color: Colors.white,
                              borderRadius: BorderRadius.all(Radius.circular(5))
                          ),
                          padding: const EdgeInsets.symmetric(vertical: 5),
                          child: Column(
                            children: [
                              Row(
                                children: [
                                  // Image.asset(roomItem.roomIcon,width: 100,height: 100,),
                                  Container(
                                    width: 73,
                                    height: 73,
                                    margin: EdgeInsets.only(left: 5),
                                    decoration: ShapeDecoration(
                                        image: DecorationImage(
                                          // image:index % 2 == 0 ? AssetImage(Assets.homeAvatar1) : AssetImage(Assets.homeAvatar2),
                                            image: NetworkImage(
                                                roomItem.roomIcon ?? ''),
                                            fit: BoxFit.fitWidth),
                                        shape: RoundedRectangleBorder(
                                            borderRadius:
                                            BorderRadiusDirectional
                                                .circular(8))),
                                    // BoxDecoration(
                                    //     borderRadius: BorderRadius.all(Radius.circular(10))
                                    // ),
                                    // child:  Image.asset(index % 2 == 0?Assets.homeAvatar1 : Assets.homeAvatar2,fit: BoxFit.fitWidth,),
                                  ),
                                  const SizedBox(
                                    width: 5,
                                  ),
                                  Expanded(
                                    child: SizedBox(
                                      height: 73,
                                      child: Column(
                                        crossAxisAlignment:
                                        CrossAxisAlignment.start,
                                        mainAxisAlignment:
                                        MainAxisAlignment.spaceBetween,
                                        children: [
                                          Column(
                                            crossAxisAlignment:
                                            CrossAxisAlignment.start,
                                            children: [
                                              Row(
                                                children: [
                                                  roomItem.countryUrl != null
                                                      ? Image.network(
                                                    roomItem.countryUrl,
                                                    width: 30,
                                                    height: 20,
                                                  )
                                                      : const Image(
                                                    image: AssetImage(Assets
                                                        .homeCountries),
                                                    width: 30,
                                                    height: 20,
                                                  ),
                                                  SizedBox(
                                                    width: 3,
                                                  ),
                                                  SizedBox(
                                                    width: 180,
                                                    child: Text(
                                                      roomItem.roomName,
                                                      softWrap: false,
                                                      maxLines: 1,
                                                      overflow:
                                                      TextOverflow.ellipsis,
                                                    ).fontSize(16),
                                                  )
                                                ],
                                              ),
                                              Text(
                                                roomItem.slogan ?? "",
                                                softWrap: false,
                                                maxLines: 1,
                                                overflow: TextOverflow.ellipsis,
                                              ).fontSize(12).color(
                                                  const Color(0xffC1C1C1)),
                                            ],
                                          ),
                                          Row(
                                            children: [
                                              roomItem.categoryTypeIcon != null
                                                  ? Image.network(
                                                roomItem.categoryTypeIcon,
                                                width: 24,
                                              )
                                                  : const Image(
                                                image: AssetImage(Assets
                                                    .homeIcRoomLove),
                                                width: 24,
                                              ),
                                              const SizedBox(
                                                width: 4,
                                              ),
                                              Container(
                                                padding: EdgeInsets.fromLTRB(
                                                    8, 1, 8, 1),
                                                decoration: BoxDecoration(
                                                    borderRadius:
                                                    BorderRadius.all(
                                                        Radius.circular(
                                                            10)),
                                                    color: Color(newBgColors)),
                                                child: Text(roomItem
                                                    .roomCategoryName)
                                                    .fontSize(10)
                                                    .colorInt(newColors),
                                              ),
                                              const Spacer(),
                                              const Image(
                                                image: AssetImage(
                                                  Assets.homeIcFire,
                                                ),
                                                width: 12,
                                                height: 12,
                                              ),
                                              const SizedBox(
                                                width: 5,
                                              ),
                                              Text(roomItem.scoreWeight
                                                  .toString())
                                                  .fontSize(12)
                                                  .colorInt(0xffC1C1C1),
                                            ],
                                          ),
                                        ],
                                      ),
                                    ).marginLeft(10).paddingRight(8.0),
                                  )
                                ],
                              )
                                  .roundedRect(8)
                                  .paddingAll(5)
                                  .colorBg(bgColor: Colors.white)
                                  .onClick(() {
                                _homeController.joinRoomPage(context,roomItem);
                                // Get.to(() => PostDetailPage());
                              }),
                            ],
                          ),
                        );
                      },
                    )
                        : Center(
                      child: Image.asset(
                        Assets.noData,
                        fit: BoxFit.fill,
                      ),
                    ),
                  ),
                ],
              ),
            )
        )).marginBottom(60);
  }
// joinRoomPage
  /// 进入房间
  void joinRoomPage(BuildContext context, Recommend model) {
// ChatRoomEnterModel
    /// 进入房间要用的模型
    KHChatRoomEnterModel enterModel = KHChatRoomEnterModel();
    enterModel.enterRoomNo = model.roomNo;
    if (model.rangeTypeStr != null) {
      enterModel.rangeType = int.parse(model.rangeTypeStr!);
    }
    enterModel.template = model.roomTemplateId;
    /// 基础数据
    KHChatRoomInfoModel roomInfoModel = KHChatRoomInfoModel();
    roomInfoModel.roomCategoryId = model.roomCategoryId;
    roomInfoModel.icon = model.roomIcon;
    roomInfoModel.roomNo = model.roomNo;
    roomInfoModel.name = model.roomName;
    roomInfoModel.name = model.roomName;
    roomInfoModel.roomTemplateId = model.roomTemplateId;
    roomInfoModel.roomCode = model.roomCode;
    enterModel.roomBaseInfoModel = roomInfoModel;
    if (model.roomNo != null) {
      RoomPage.show(context, int.parse(model.roomNo!).toString());
    }
  }
  Widget homeSwiper(BuildContext context, controller) {
    return Container(
      width: MediaQuery.of(context).size.width - 20,
      height: 88.h,
      margin: const EdgeInsets.only(left: 10),
      child: Stack(
        children: [
          ClipRRect(
              borderRadius: BorderRadius.circular(10.0),
              child:
              CarouselSlider.builder(
                itemCount: imgList.length,
                itemBuilder:(BuildContext context, int index, int pageViewIndex){
                  return GestureDetector(
                    onTap: () {
                    },
                    child: ClipRRect(
                        borderRadius: BorderRadius.circular(10.0),
                        child:Image(image: AssetImage('assets/images/home/rooms_banner.png'),width: MediaQuery.of(context).size.width - 24 ,height:88.h,fit: BoxFit.fill,)
                    ),
                  );
                } ,
                options: CarouselOptions(
                    height: 88.0,
                    autoPlay: true, // 自动播放
                    aspectRatio: 345 / 88, // 宽高比
                    viewportFraction: 1.0,
                    enlargeCenterPage: false,
                    onPageChanged: (index, reason) {
                      setState(() {
                        swiperIndex = index;
                      });
                    }
                ),
              )
          ),
          Positioned(
              top: 70.h,
              left: (MediaQuery.of(context).size.width - 20)/2 - 10,
              child: Row(
                  children: List.generate(imgList.length, (index) =>
                      Container(
                        width:index == swiperIndex? 10 : 5,
                        height: 4,
                        margin: const EdgeInsets.only(right: 2),
                        decoration: BoxDecoration(
                            color:index == swiperIndex?Colors.white : const Color(0xffBFBFBF),
                            borderRadius: BorderRadius.all(Radius.circular(5))
                        ),
                      )
                  )
              )
          )
        ],
      ),
    );
  }
  Widget _countries(BuildContext context) {
    return ChangeNotifierProvider(
        create: (_) => SelectCountryModel(),
        child: Consumer<SelectCountryModel>(
          builder: (context, model, _) {
            final filteredList = model.countryList;
            return Container(
              padding: const EdgeInsets.symmetric(vertical: 10),
              child: SizedBox(
                height: 130.h,
                child: listWidget(context, model, filteredList),
              ),
            );
          },
        ));
  }
  Widget listWidget(context, model, filteredList) {
    if (model.countryList.isEmpty) {
      return Container(
        transform: Matrix4.translationValues(0, -20, 0),
        child: JREmptyView(
            desc: T.current.h1_no_more,
            imgSize:const Size(200,90)
        ),
      );
    }
    return GridView.builder(
      gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
        maxCrossAxisExtent: MediaQuery.sizeOf(context).width * .25, // 每个项目的最大宽度
        crossAxisSpacing: 15,
        mainAxisSpacing: 20,
        childAspectRatio: 1.5,
      ),
      itemCount: 8,
      itemBuilder: (context, index) {
        return getItem(filteredList[index]);
      },
    );
    Wrap(
      direction: Axis.horizontal,
      spacing: (MediaQuery.sizeOf(context).width ) * .2 / 4,
      // 行间距
      runSpacing: 20,
      children: List.generate(8, (index) => getItem(filteredList[index])),
    );
  }
  Widget getItem(item) {
    return SizedBox(
      width: MediaQuery.sizeOf(context).width * .2,
      child: Column(
        children: [
          Image.network(
            item.flag,
            width: 36.w,
            height: 28.h,
            fit: BoxFit.fill,
          ),
          const SizedBox(
            height: 10,
          ),
          Text(
            item.abbreviation ?? '',
            style: const TextStyle(overflow: TextOverflow.ellipsis),
          ).color(const Color(0xffA8A8A8)).fontSize(12)
        ],
      ).center(),
    ).onTap(() {
      Get.to(HomeCountriesPage(
        country: item.country,
      ));
      setState(() {
        country = item.country;
      });
    });
  }
  Widget _popular(BuildContext context, controller) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const SizedBox(
          height: 15,
        ),
        popularSwiper(context,controller),
        const SizedBox(
          height: 15,
        ),
        Expanded(
            child: PopularTabsWidget(
              callback: (val) {
                final throttledFunction = throttle(() {
                  onDataChange(val);
                }, const Duration(milliseconds: 1000));
                throttledFunction();
              },
              controller: controller,
            ))
      ],
    ).paddingSymmetric(horizontal: 16);
  }
  Widget popularSwiper(BuildContext context, controller) {
    return DefaultTabController(
        length: 3,
        child: Container(
            height: 108.h,
            decoration: const BoxDecoration(
                image: DecorationImage(
                    image: AssetImage(Assets.popularBg), fit: BoxFit.fill)),
            child: Column(
              children: [
                const SizedBox(height: 2,),
                SizedBox(
                  height: 17.h,
                  child: Center(
                    child: Text(scrollerOffset == 0?T.current.h1_top_room:scrollerOffset == 1?T.current.h1_top_gifter_room:T.current.h1_top_charm_room)
                        .color(Colors.white)
                        .fontSize(14)
                        .fontWeight(FontWeight.bold),
                  ),
                ),
                Expanded(
                  child: CarouselSlider.builder(
                    itemCount: topNameList.length,
                    itemBuilder:(BuildContext context, int index, int pageViewIndex){
                      return GestureDetector(
                        onTap: () {},
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            const SizedBox(
                              width: 20,
                            ),
                            Stack(
                              children: [
                                Positioned(
                                  top: 30.h,
                                  left: 9.5.w,
                                  child: Image.asset(
                                    Assets.popularIcBottomTwo,
                                    width: 45.w,
                                    height: 54.h,
                                  ),
                                ),
                                Container(
                                    transform: Matrix4.translationValues(0, -15.w, 0),
                                    width: 64.w,
                                    height: 100.h,
                                    child: Image.asset(
                                      Assets.popularIcTopTwo,
                                      width: 64.w,
                                      height: 52.h,
                                    )),
                                Positioned(
                                  left: 13.w,
                                  top: 17.h,
                                  child: Container(
                                    width: 38.w,
                                    height: 38.w,
                                    decoration: BoxDecoration(
                                        borderRadius: BorderRadius.circular(100),
                                        image: DecorationImage(
                                            image:AssetImage(
                                              controller.popularTopList
                                                  .value.length > 0?
                                              controller.popularTopList
                                                  .value[scrollerOffset * 3 + 1].headPortraitsUrl : Assets.homeAvatar1,
                                            ),
                                            // controller.popularTopList.value.length >
                                            //         0
                                            //     ?
                                            //     : AssetImage(Assets.homeAvatar1),
                                            fit: BoxFit.cover)),
                                  ),
                                ),
                                Positioned(
                                    left: 18.w,
                                    top: 55.h,
                                    child: Text(T.current.h1_top_two_room)
                                        .color(Colors.white)
                                        .fontSize(13))
                              ],
                            ),
                            Stack(
                              children: [
                                Positioned(
                                  top: 30.h,
                                  left: 9.5.w,
                                  child: Image.asset(
                                    Assets.popularIcBottomOne,
                                    width: 45.w,
                                    height: 54.h,
                                  ),
                                ),
                                Container(
                                    transform: Matrix4.translationValues(0, -15, 0),
                                    width: 64.w,
                                    height: 100.h,
                                    child: Image.asset(
                                      Assets.popularIcTopOne,
                                      width: 64.w,
                                      height: 52.h,
                                    )),
                                Positioned(
                                  left: 13.w,
                                  top: 17.h,
                                  child: Container(
                                    width: 38.w,
                                    height: 38.w,
                                    decoration: BoxDecoration(
                                        borderRadius: BorderRadius.circular(100),
                                        image: DecorationImage(
                                            image:
                                            AssetImage(
                                              controller.popularTopList
                                                  .value.length > 0?
                                              controller.popularTopList
                                                  .value[scrollerOffset * 3].headPortraitsUrl : Assets.homeAvatar1,
                                            ),
                                            fit: BoxFit.fitWidth)),
                                  ),
                                ),
                                Positioned(
                                    left: 20.w,
                                    top: 55.h,
                                    child: Text(T.current.h1_top_one_room)
                                        .color(Colors.white)
                                        .fontSize(13))
                              ],
                            ),
                            Stack(
                              children: [
                                Positioned(
                                  top: 30.h,
                                  left: 9.5.w,
                                  child: Image.asset(
                                    Assets.popularIcBottomThree,
                                    width: 45.w,
                                    height: 54.h,
                                  ),
                                ),
                                Container(
                                    transform: Matrix4.translationValues(0, -15, 0),
                                    width: 64.w,
                                    height: 100.h,
                                    child: Image.asset(
                                      Assets.popularIcTopThree,
                                      width: 64.w,
                                      height: 52.h,
                                    )),
                                Positioned(
                                  left: 13.w,
                                  top: 17.h,
                                  child: Container(
                                    width: 38.w,
                                    height: 38.w,
                                    decoration: BoxDecoration(
                                        borderRadius: BorderRadius.circular(100),
                                        image: DecorationImage(
                                            image:AssetImage(
                                              controller.popularTopList
                                                  .value.length > 0?
                                              controller.popularTopList
                                                  .value[scrollerOffset * 3 + 2].headPortraitsUrl : Assets.homeAvatar1,
                                            ),
                                            fit: BoxFit.fitWidth)),
                                  ),
                                ),
                                Positioned(
                                    left: 18.w,
                                    top: 55.h,
                                    child: Text(T.current.h1_top_three_room)
                                        .color(Colors.white)
                                        .fontSize(13))
                              ],
                            ),
                            const SizedBox(
                              width: 20,
                            ),
                          ],
                        ),
                      );
                    } ,
                    options: CarouselOptions(
                        height: 88.0,
                        autoPlay: true, // 自动播放
                        aspectRatio: 345 / 88, // 宽高比
                        viewportFraction: 1.0,
                        enlargeCenterPage: false,
                        scrollDirection: Axis.vertical,
                        onPageChanged: (index, reason) {
                          setState(() {
                            scrollerOffset = index;
                          });
                        }
                    ),
                  ),
                ),
              ],
            )
        )
    );
  }
  Widget _mine(BuildContext context, controller) {
    final navBarProvider = Provider.of<MainPageModel>(context);
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const SizedBox(
          height: 15,
        ),
        Container(
          height: 76.h,
          padding: const EdgeInsets.all(15),
          decoration: const BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.all(Radius.circular(12))),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Container( //
                width: 44.w,
                height: 44.w,
                margin: const EdgeInsets.only(right: 5),
                decoration: const BoxDecoration(
                    image: DecorationImage(image: AssetImage(Assets.mineCreateRoom), fit: BoxFit.fill)
                ),
              ),
              Expanded(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      T.current.h1_create_room,
                    ).fontWeight(FontWeight.bold).fontSize(16),
                    Text('${T.current.h1_enjoy_room}!!!')
                        .color(const Color(0xffc1c1c1))
                  ],
                ),
              ),
              Container(
                  height: 38.w,
                  width: 38.h,
                  decoration: BoxDecoration(
                    gradient: const LinearGradient(
                      colors: [Color(0xff8A72FE), Color(0xff6549EC)],
                      begin: Alignment.topCenter,
                      end: Alignment.bottomCenter,
                    ),
                    borderRadius: BorderRadius.circular(38.w),
                  ),
                  child:Center(
                    child: Image.asset(Assets.mineAddRoom,fit: BoxFit.fill,
                      width: 24,
                      height: 24,
                    ),
                  )
                // ElevatedButton(
                //   onPressed: () async {
                //     var res = await _homeController.CheckRoomState();
                //     if (res) {
                //       navBarProvider.changeBottomState(false);
                //       DrawerAddRoomKey.currentState?.open();
                //       _homeController.loadRoomTags();
                //     }
                //   },
                //   style: ElevatedButton.styleFrom(
                //     backgroundColor: Colors.transparent, // 设置按钮背景为透明
                //     shadowColor: Colors.transparent, // 去掉阴影
                //     padding: const EdgeInsets.symmetric(
                //         horizontal: 10.0, vertical: 0),
                //     shape: RoundedRectangleBorder(
                //       borderRadius: BorderRadius.circular(8.0),
                //     ),
                //   ),
                //   child: Text(T.current.h1_enjoy_room_1).color(Colors.white),
                // ),
              ).onClick(() async {
                var res = await _homeController.CheckRoomState();
                if (res) {
                  navBarProvider.changeBottomState(false);
                  DrawerAddRoomKey.currentState?.open();
                  _homeController.loadRoomTags();
                }
              })
            ],
          ),
        ),
        const SizedBox(
          height: 15,
        ),
        Expanded(
            child: MineTabsWidget(
              callback: (val) {
                onDataChangeMine(val);
              },
              controller: controller,
            ))
      ],
    ).paddingSymmetric(horizontal: 16);
  }
  @override
  Widget build(BuildContext context) {
    return GetBuilder<HomeController>(builder: (controller) {
      return Scaffold(
          backgroundColor: Colors.transparent,
          body: PopScope(
            child: GestureDetector(
              onPanUpdate:(details){
                if (details.delta.dx > 0) {
                  // 拦截左滑手势
                }
              },
              child: body(controller),
            ),
          )
      );
    });
  }
  @override
  void dispose() {
    Get.delete<HomeController>(force: true);
    _tabController.dispose();
    _childController.performAction();
    super.dispose();
  }
}
class _SliverPersistentHeaderDelegate extends SliverPersistentHeaderDelegate {
  final Widget child;
  final double height;
  _SliverPersistentHeaderDelegate(this.child, this.height);
  @override
  Widget build(
      BuildContext context, double shrinkOffset, bool overlapsContent) {
    return child;
  }
  @override
  double get maxExtent => height;
  @override
  double get minExtent => height;
  @override
  bool shouldRebuild(SliverPersistentHeaderDelegate oldDelegate) {
    return true;
  }
}